package com.gurid.service.oss.service.impl;

import com.google.gson.Gson;
import com.gurid.service.oss.util.OssProperties;
import com.gurid.service.oss.service.FileService;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private OssProperties properties;

    @Override
    public String upload(InputStream inputStream, String module, String oringianlFilename) {

        //1.构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.regionAs0());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);

        //2.读取配置信息，然后准备上传
        String domain = properties.getDomain();
        String bucket = properties.getBucket();
        String accessKey = properties.getAccesskey();
        String secretKey = properties.getSecretkey();

        //3.生成上传凭证
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        //4.默认不指定key的情况下，以文件内容的hash值作为文件名
        String folder = LocalDate.now().format(DateTimeFormatter.ofPattern("/yyyy/MM/dd/"));
        System.out.println(folder);
        String key = module + folder + UUID.randomUUID() + ".jpg";
        try {
            Response response = uploadManager.put(inputStream,key,upToken,null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            ex.printStackTrace();
            if (ex.response != null) {
                System.err.println(ex.response);
                try {
                    String body = ex.response.toString();
                    System.err.println(body);
                } catch (Exception ignored) {
                }
            }
        }
        //5.返回文件的url
        //http://sc6vzb7ct.hd-bkt.clouddn.com/ddf912ab-4f4c-46a1-b26e-c77b76d41dbe.png-gurid
        /*String url = domain + "/" + key + "-gurid";
        System.out.println("上传成功：" + url);
        delete(url);
        return url;*/
        return domain + "/" + key;
    }

    @Override
    public void delete(String url) {
        Configuration cfg = new Configuration(Region.region0());
        String domain = properties.getDomain() + "/";
        String accessKey = properties.getAccesskey();
        String secretKey = properties.getSecretkey();
        String bucket = properties.getBucket();

        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);

        String key = StringUtils.removeStart(url, domain);
        try {
            bucketManager.delete(bucket, key);
            System.out.println(url + "删除成功");
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }
}
